<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区 -->
    <el-card class="box-card">
      <!-- 添加搜索区域 -->
      <el-row :gutter="40">
        <el-col :span="7">
          <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable>
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 用户列表 -->
      <el-table :data="userList" border stripe style="width: 100%">
        <el-table-column type="index" label="#">
        </el-table-column>
        <el-table-column prop="loginAcct" label="用户名" width="180">
        </el-table-column>
        <el-table-column label="角色" width="180">
          <template v-slot="scope">
            <el-tag v-for="role in scope.row.roleList" :key="role.id">{{role.name}}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="用户描述" width="180">
        </el-table-column>
        <el-table-column prop="telephone" label="电话" width="180">
        </el-table-column>
        <el-table-column prop="email" label="邮箱" width="180">
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间">
        </el-table-column>
        <el-table-column prop="updateTime" label="最后修改时间">
        </el-table-column>
        <el-table-column label="状态" width="65px">
          <template v-slot="scope">
            <el-switch v-model="scope.row.active" @change="userStateChanged(scope.row)">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <!-- 插槽域使用 -->
          <template v-slot="scope">
            <el-tooltip class="item" effect="dark" content="修改用户" placement="top" :hide-after="1000">
              <el-button type="primary" icon="el-icon-edit" size="small " circle @click="showEditDialog(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="删除用户" placement="top" :hide-after="1000">
              <el-button type="danger" icon="el-icon-delete" size="small " circle @click="removeUser(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="分配角色" placement="top" :hide-after="1000">
              <el-button type="success" icon="el-icon-setting" size="small " circle @click="assignRole(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 添加用户表单的对话框 -->
      <el-dialog title="添加用户" :visible.sync="addDialogVisible" id="addUser" @close="addDialogClose">
        <!-- 内容主体区 -->
        <el-form :model="addForm" :rules="addRules" ref="addForm" label-width="70px">
          <el-form-item label="用户名" prop="loginAcct">
            <el-input v-model="addForm.loginAcct"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="addForm.password" type="password"></el-input>
          </el-form-item>
          <el-form-item label="电话" prop="telephone">
            <el-input v-model="addForm.telephone"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="addForm.email"></el-input>
          </el-form-item>
        </el-form>
        <!-- 底部区 -->
        <div slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addUserConfirm">确 定</el-button>
        </div>
      </el-dialog>
      <!-- 修改用户的对话框表单 -->
      <el-dialog title="修改用户" :visible.sync="editDialogVisible" id="editUser" @close="editDialogClose">
        <!-- 内容主体区 -->
        <el-form :model="editForm" :rules="editRules" ref="editForm" label-width="70px">
          <el-form-item label="用户名" prop="loginAcct">
            <el-input v-model="editForm.loginAcct" placeholder="请输入用户名"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="editForm.password" type="password" placeholder="请输入密码,不输入则不修改"></el-input>
          </el-form-item>
          <el-form-item label="电话" prop="telephone">
            <el-input v-model="editForm.telephone" placeholder="请输入电话"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="editForm.email" placeholder="请输入邮箱"></el-input>
          </el-form-item>
        </el-form>
        <!-- 底部区 -->
        <div slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editUserConfirm">确 定</el-button>
        </div>
      </el-dialog>
      <!-- 分配角色的对话框 -->
      <el-dialog title="分配角色" :visible.sync="showAssianRoleDialogVisible" width="50%" @close="assginRoleClose">
        <div style="text-align: left; display: inline-block; position: relative; top: 50% ;left: 50%; transform: translate(-50%);">
          <el-transfer v-model="roleValue" :data="roleData" :titles="['未分配角色', '已分配角色']"></el-transfer>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="showAssianRoleDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="assignRoleConfirm">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 分页区域 -->
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="queryInfo.pageNum"
        :page-sizes="[5, 10, 15, 20]" :page-size="queryInfo.pageSize" layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </el-card>
  </div>
</template>

<script>
export default {
  data () {
    // 验证邮箱的规则
    var checkEmail = (rule, value, callback) => {
      const regEmail = /^([a-zA-z0-9_-])+@([a-zA-z0-9_-])+(\.[a-zA-z0-9_-])+/
      if (regEmail.test(value)) {
        return callback()
      }
      callback(new Error('请输入合法邮箱'))
    }
    return {
      // 获取用户列表参数
      queryInfo: {
        query: '',
        pageNum: 1,
        pageSize: 5
      },
      userList: [],
      total: 0,
      // 控制对话框的隐藏是否
      addDialogVisible: false,
      // 添加用户的表单数据
      addForm: {
        loginAcct: '',
        password: '',
        email: '',
        telephone: ''
      },
      addRules: {
        loginAcct: [{
          required: true,
          message: '请输入用户名',
          trigger: 'blur'
        },
        {
          min: 3,
          max: 20,
          message: '长度在 3 到 20 个字符',
          trigger: 'blur'
        }
        ],
        password: [{
          required: true,
          message: '请输入密码',
          trigger: 'blur'
        },
        {
          min: 6,
          max: 30,
          message: '长度在 6 到 30 个字符',
          trigger: 'blur'
        }
        ],
        email: [{
          required: true,
          message: '请输入密码',
          trigger: 'blur'
        },
        {
          validator: checkEmail,
          trigger: 'blur'
        }
        ],
        telephone: [{
          required: true,
          message: '请输入密码',
          trigger: 'blur'
        }]
      },
      // 控制修改用户显示与否
      editDialogVisible: false,
      editForm: {
        id: '',
        loginAcct: '',
        password: '',
        email: '',
        telephone: ''
      },
      editRules: {
        loginAcct: [{
          required: true,
          message: '请输入用户名',
          trigger: 'blur'
        },
        {
          min: 3,
          max: 20,
          message: '长度在 3 到 20 个字符',
          trigger: 'blur'
        }
        ],
        email: [{
          required: true,
          message: '请输入密码',
          trigger: 'blur'
        },
        {
          validator: checkEmail,
          trigger: 'blur'
        }
        ],
        telephone: [{
          required: true,
          message: '请输入密码',
          trigger: 'blur'
        }]
      },
      // 控制分配角色对话框的显示
      showAssianRoleDialogVisible: false,
      roleData: [],
      roleValue: [],
      adminUseId: ''
    }
  },
  created () {
    this.getUserList()
  },
  methods: {
    async getUserList () {
      const {
        data: res
      } = await this.$http.post('users/list', this.queryInfo)
      if (res.result !== 'SUCCESS') {
        return this.$message.error('获取列表失败')
      }
      this.userList = res.data.userList.list
      this.total = res.data.userList.total
      console.info(this.userList)
    },
    handleSizeChange (newPageSize) {
      this.queryInfo.pageSize = newPageSize
      this.getUserList()
    },
    handleCurrentChange (newPageNum) {
      this.queryInfo.pageNum = newPageNum
      this.getUserList()
    },
    async updateUser (userPO) {
      const {
        data: res
      } = await this.$http.post('users/list/edit', userPO)
      if (res.result !== 'SUCCESS') {
        return this.$message.error('更新失败')
      }
      this.getUserList()
    },
    userStateChanged (userInfo) {
      if (userInfo.status === 1) {
        userInfo.status = 0
      } else {
        userInfo.status = 1
      }
      this.updateUser(userInfo)
    },
    addDialogClose () {
      this.$refs.addForm.resetFields()
    },
    addUserConfirm () {
      this.$refs.addForm.validate(async valid => {
        if (!valid) {
          return null
        }
        const {
          data: res
        } = await this.$http.post('users/list/add', this.addForm)
        if (res.result !== 'SUCCESS') {
          this.$message.error(res.message)
        } else {
          this.$message.success('添加用户成功')
          this.addDialogVisible = false
          this.getUserList()
          this.queryInfo.pageNum = 1000000
        }
      })
    },
    // 显示修改对话框并回显
    showEditDialog (userInfo) {
      this.editForm.loginAcct = userInfo.loginAcct
      this.editForm.email = userInfo.email
      this.editForm.telephone = userInfo.telephone
      this.editForm.id = userInfo.id
      this.editDialogVisible = true
    },
    editDialogClose () {
      this.$refs.editForm.resetFields()
    },
    editUserConfirm () {
      this.$refs.editForm.validate(async valid => {
        if (!valid) {
          return null
        }
        const {
          data: res
        } = await this.$http.post('users/list/edit', this.editForm)
        if (res.result !== 'SUCCESS') {
          this.$message.error(res.message)
        } else {
          this.$message.success('修改用户成功')
          this.editDialogVisible = false
          this.getUserList()
        }
      })
    },
    // 删除用户信息
    async removeUser (userInfo) {
      // 询问是否删除
      const confirmResult = await this.$confirm('此操作将永久删除该用户:' + userInfo.loginAcct + ', 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(error => {
        return error
      })
      if (confirmResult === 'confirm') {
        const {
          data: res
        } = await this.$http.get('users/list/delete', {
          params: {
            id: userInfo.id
          }
        })
        if (res.result !== 'SUCCESS') {
          this.$message.error(res.message)
        } else {
          this.$message.success('删除用户成功')
          this.getUserList()
        }
      } else {
        this.$message.info('取消删除用户')
      }
    },
    // 分配角色对话框
    async assignRole (userInfo) {
      this.adminUseId = userInfo.id
      const {
        data: res
      } = await this.$http.post('auth/roles/list')
      if (res.result !== 'SUCCESS') {
        this.$message.error(res.message)
      }
      var roleList = res.data.roleList
      roleList.forEach(item => {
        this.roleData.push({
          key: item.id,
          label: item.name
        })
      })
      var hasAssignedAuthList = userInfo.roleList
      hasAssignedAuthList.forEach(item =>
        this.roleValue.push(item.id)
      )
      this.showAssianRoleDialogVisible = true
    },
    async assignRoleConfirm () {
      const data = {
        adminUseId: this.adminUseId,
        roleIdList: this.roleValue.join(',')
      }
      const Jsondata = this.$qs.stringify(data)
      const {
        data: res
      } = await this.$http.post('users/role/edit', Jsondata)
      if (res.result !== 'SUCCESS') {
        this.$message.error(res.message)
      }
      this.showAssianRoleDialogVisible = false
    },
    assginRoleClose () {
      this.getUserList()
      this.adminUseId = ''
      this.roleValue = []
      this.roleData = []
    }
  },
  computed: {}
}
</script>

<style lang="less" scoped>
  .el-breadcrumb {
    margin-bottom: 20px;
    font-size: 16px;
  }

  .el-card {}

  .el-table {
    margin-top: 15px;
    font-size: 14px;
  }

  .el-form .el-input {
    width: 60%;
  }

  .el-tag {
    margin: 5px;
  }
</style>
